<template>
  <div class="content-warp">
    <div class="card-box">
      <div class="content-warp_title">{{ infoDetail.fullname || '-' }}</div>
      <div class="content-warp-subtitle">
        <div class="content-warp_title-item">
          <div class="content-warp_title-item-label">负责人</div>
          <div class="content-warp_title-item-value">
            <dc-view v-model="infoDetail.personInChargeUser" objectName="user" showKey="realName" />
          </div>
        </div>
        <div class="content-warp_title-item">
          <div class="content-warp_title-item-label">客户分类</div>
          <div class="content-warp_title-item-value">
            <dc-dict type="text" :options="DC_CRM_CUS_CATEGORY" :value="infoDetail.cusCategory" />
          </div>
        </div>
        <div class="content-warp_title-item">
          <div class="content-warp_title-item-label">法定代表人</div>
          <div class="content-warp_title-item-value">
            {{ infoDetail.legalPerson || '-' }}
          </div>
        </div>
        <div class="content-warp_title-item">
          <div class="content-warp_title-item-label">客户级别</div>
          <div class="content-warp_title-item-value">
            <dc-dict type="text" :options="DC_CRM_CUS_LEVEL" :value="infoDetail.cusLevel" />
          </div>
        </div>
      </div>
      <div class="operate-container">
        <el-button type="primary" @click="handleDemandAdd">添加客户需求表</el-button>
        <el-button type="primary" @click="handleAddOpps">添加客户商机</el-button>
        <el-button type="primary" @click="handleAdd">添加跟进记录</el-button>
        <el-button v-if="infoDetail.cusShareType != '1853709453308252161'" @click="handleShared"
          >加入共享
        </el-button>
        <el-button v-else @click="handlerPivate">移至私有</el-button>
        <el-button @click="handleUpdata">编辑</el-button>
        <el-button @click="handleDelete">删除</el-button>
      </div>
    </div>
    <div class="card-box">
      <el-tabs v-model="activeName">
        <el-tab-pane label="详情" name="detail">
          <DetailComp :infoDetail="infoDetail"></DetailComp>
        </el-tab-pane>
        <el-tab-pane label="客户需求表" name="demand">
          <DemandComp ref="demandComp"></DemandComp>
        </el-tab-pane>
        <el-tab-pane label="跟进记录" name="record">
          <RecordComp ref="recordComp"></RecordComp>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>

  <el-drawer v-model="open.dialogVisible" width="600px" :title="open.title" @close="cancel">
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="关联商机" id="oppsId" prop="oppsId">
        <dc-select-dialog
          v-model="formData.oppsId"
          type="input"
          objectName="opps"
          placeholder="请选择关联商机"
          :multiple="false"
          :params="{
            customerId: route.params.id,
          }"
        />
      </el-form-item>

      <el-form-item label="跟进时间" prop="followDate">
        <el-date-picker
          v-model="formData.followDate"
          type="datetime"
          placeholder="请选择"
          format="YYYY/MM/DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
          class="form-item-row"
        />
      </el-form-item>
      <el-form-item label="跟进类型" prop="followId">
        <el-select v-model="formData.followId" clearable placeholder="请选择">
          <el-option
            v-for="item in DC_CRM_FOLLOW_TYPE"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上传附件" id="attachments" prop="attachments">
        <dc-upload
          v-model="formData.attachments"
          :limit="10"
          :targetType="Const.targetType.CUSTOMER"
        />
      </el-form-item>
      <el-form-item label="跟进详情" prop="followContent">
        <el-input
          v-model="formData.followContent"
          type="textarea"
          placeholder="请输入备注信息"
          :autosize="{ minRows: 5 }"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </template>
  </el-drawer>

  <el-drawer
    v-model="demandOpen.demandDialog"
    width="600px"
    :title="demandOpen.demandTitle"
    @close="cancel"
  >
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="需求编码" prop="followDate">
        <div>由系统生成</div>
      </el-form-item>
      <el-form-item label="需求名称" prop="rlistName">
        <el-input v-model="formData.rlistName" placeholder="请输入需求名称" />
      </el-form-item>
      <el-form-item label="关联商机" id="oppsId" prop="oppsId">
        <dc-select-dialog
          v-model="formData.oppsId"
          type="input"
          objectName="opps"
          placeholder="请选择关联商机"
          :multiple="false"
          :params="{
            customerId: route.params.id,
          }"
        />
      </el-form-item>
      <el-form-item label="上传附件" id="attachments" prop="attachments">
        <dc-upload
          v-model="formData.attachments"
          :limit="10"
          :targetType="Const.targetType.CUSTOMER"
        />
      </el-form-item>
      <el-form-item label="备注信息" prop="followContent">
        <el-input
          v-model="formData.followContent"
          type="textarea"
          placeholder="请输入备注信息"
          :autosize="{ minRows: 5 }"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </template>
  </el-drawer>

  <el-dialog v-model="sharedOpen.dialogVisible" :title="sharedOpen.title" width="1500">
    <CrudView
      ref="userRef"
      :config="userConfig"
      :ids="formData.oppsId"
      :maxSelectionCount="10000"
      :searchLabelWidth="120"
      :delBtn="false"
      :editBtn="false"
      :addBtn="false"
      :menu="false"
    ></CrudView>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="sharedOpen.dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="sharedconfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup name="MyClientsDetail">
import { ref, reactive, onMounted, toRefs, getCurrentInstance } from 'vue';
import Api from '@/api/index';

import DetailComp from './components/detail.vue';
import RecordComp from './components/record.vue';
import DemandComp from './components/demand.vue';
import { useRoute, useRouter } from 'vue-router';
import Const from '@/const';

const recordComp = ref();
const demandComp = ref();
const route = useRoute(); // 获取当前路由对象
const router = useRouter();

const { proxy } = getCurrentInstance();

const { DC_CRM_FOLLOW_TYPE, DC_CRM_CUS_CATEGORY, DC_CRM_CUS_LEVEL, DC_CRM_CUS_SHARE_TYPE } =
  proxy.useCache([
    { key: 'DC_CRM_FOLLOW_TYPE' },
    { key: 'DC_CRM_CUS_CATEGORY' },
    { key: 'DC_CRM_CUS_LEVEL' },
    { key: 'DC_CRM_CUS_SHARE_TYPE' },
  ]);

const pageData = reactive({
  infoDetail: {},
  activeName: 'detail',
  open: {
    dialogVisible: false,
    title: '',
  },
  sharedOpen: {
    dialogVisible: false,
    title: '',
  },
  demandOpen: {
    demandDialog: false,
    demandTitle: '',
  },
  rules: {
    oppsId: [{ required: true, message: '请选择', trigger: 'blur' }],
    // attachments: [{ required: true, message: '请选择附件', trigger: 'blur' }],
  },
  formData: {},
  tableData: {},
  loading: false,
  userRef: null,
  userConfig: {
    operate: {
      get: Api.system.user.getList,
    },
    column: [
      {
        label: '姓名',
        prop: 'realName',
        search: true,
      },
      {
        label: '所属部门',
        prop: 'deptName',
        search: true,
      },
      {
        label: '职务',
        prop: 'postName',
      },
    ],
  },

  //   客户需求表
  demandRef: null,
  demandConfig: {
    operate: {
      get: Api.system.user.getList,
    },
    column: [
      {
        label: '姓名',
        prop: 'realName',
        search: true,
      },
      {
        label: '所属部门',
        prop: 'deptName',
        search: true,
      },
      {
        label: '职务',
        prop: 'postName',
      },
    ],
  },
});
const {
  activeName,
  infoDetail,
  open,
  rules,
  formData,
  tableData,
  loading,
  sharedOpen,
  userRef,
  userConfig,
  demandOpen,
} = toRefs(pageData);

onMounted(() => {
  if (route.params.id !== 'create') getData(route.params.id);
  const time = setTimeout(() => {
    getData();
    clearTimeout(time);
  });
});

// 详情数据
const getData = async () => {
  const RouteParams = {
    id: route.params.id,
  };
  const res = await Api.crm.customer.getDetail(RouteParams);
  const { code, data } = res.data;
  if (code === 200) {
    infoDetail.value = data;
  }
};

const handleUpdata = () => {
  router.push({
    name: '编辑客户',
    params: { id: route.params.id },
  });
};

const handleDelete = () => {
  const configIds = { ids: route.params.id };
  proxy
    .$confirm('是否确认删除参数编号为"' + configIds.ids + '"的数据项？')
    .then(async () => {
      return await Api.crm.customer.deleteCustomerRemove(configIds);
    })
    .then(() => {
      router.push('/crm/myClients/list');
      proxy.$modale.msgSuccess('删除成功');
    })
    .catch(() => {});
};

const handleShared = async () => {
  sharedOpen.value.title = '添加共享人';
  sharedOpen.value.dialogVisible = true;
};

const handlerPivate = async () => {
  //   私有
  const form = {
    ...infoDetail.value,
    cusShareType: DC_CRM_CUS_SHARE_TYPE.value[1].id,
    attachments: proxy.arrayToIdsString({
      array: infoDetail.value.attachments,
    }),
  };
  const res = await Api.crm.customer.postCustomerSubmit(form);
  const { code, msg } = res.data;
  if (code === 200) {
    proxy.$message.success(msg);
    getData();
  }
};

const handleAdd = async () => {
  open.value.dialogVisible = true;
  open.value.title = '添加跟进记录';
  formData.value = {};
  activeName.value = 'record';
  const res = await Api.crm.opps.getOppsList();
  const { code, data } = res.data;
  if (code == 200) {
    tableData.value = data.records;
  }
};

// 保存 确认创建
const submitForm = () => {
  loading.value = true;
  proxy.$refs['ruleFormRef'].validate(async valid => {
    if (valid) {
      const form = {
        ...formData.value,
        customerId: route.params.id,
        attachments: proxy.arrayToIdsString({
          array: formData.value.attachments,
        }),
      };
      if (activeName.value == 'demand') {
        const res = await Api.crm.customerRlist.postCustomerRlistSubmit(form);
        const { code, msg } = res.data;
        if (code === 200) {
          demandOpen.value.demandDialog = false;
          proxy.$message.success(msg);
          formData.value = {};
          demandComp.value.getData();
        }
      } else if (activeName.value == 'record') {
        const res = await Api.crm.customerDetail.postContactRecordsSubmit(form);
        const { code, msg } = res.data;
        if (code === 200) {
          open.value.dialogVisible = false;
          proxy.$message.success(msg);
          formData.value = {};
          recordComp.value.getData();
        }
      }
    }
  });
  loading.value = false;
};

const sharedconfirm = async () => {
  // 使用 map 方法提取每个对象的 id
  const sharerUserIds = userRef.value.selectData.map(item => item.id);
  // 使用 join 方法将 id 数组转换成由逗号分隔的字符串
  infoDetail.value.sharerUser = sharerUserIds.join(',');
  sharedOpen.value.dialogVisible = false;
  const form = {
    ...infoDetail.value,
    cusShareType: DC_CRM_CUS_SHARE_TYPE.value[0].id,
    attachments: proxy.arrayToIdsString({
      array: infoDetail.value.attachments,
    }),
  };
  if (!infoDetail.value.sharerUser) {
    proxy.$message.error('未选择人员');
  } else {
    const res = await Api.crm.customer.postCustomerSubmit(form);
    const { code, msg } = res.data;
    if (code === 200) {
      proxy.$message.success(msg);
      getData();
    }
  }
};

/** 添加客户需求表 */
const handleDemandAdd = () => {
  router.push({
    path: `/crm/client/demandSchedule/create`,
    query: { customerId: route.params.id },
  });
};

const cancel = () => {
  demandOpen.value.demandDialog = false;
  open.value.dialogVisible = false;
};

// 跳转新建商机
const handleAddOpps = () => {
  router.push({
    path: '/crm/businessOpportunities/business/create',
    query: { customerId: route.params.id, from: 'myClients' },
  });
};
</script>
<style lang="scss" scoped>
.content-warp {
  padding: 0;
  background: transparent;
  gap: 16px;

  &_title {
    margin-bottom: 24px;
    font-weight: bold;
    font-size: 32px;
    color: #333;
    line-height: 32px;
  }

  &-item {
    background: red;
  }

  .operate-container {
    display: inline-flex;
    padding: 24px;
    border: 1px dashed #333;
    border-radius: 8px;
    background: #f6f8fa;
    gap: 12px;
  }

  :deep(.el-descriptions__label) {
    width: 110px;
    text-align: right;
    font-size: 14px;
    color: #333;
    font-weight: 600;
  }

  :deep(.el-descriptions__cell) {
    display: inline-flex;
  }
  :deep(.el-descriptions__content) {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.el-tooltip__trigger {
  width: 100%;
}
</style>
